package com.vaadin.tutorial.crm.security.authorization;
/**
 * @author: fan
 * @date: 2021/1/28 22:06
 **/

import com.vaadin.tutorial.crm.backend.entity.SysRole;
import com.vaadin.tutorial.crm.backend.service.SysRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

import java.util.Collection;
import java.util.List;

/**
 *
 *从数据库匹配用户访问的路径，并返回有权限访问该路径的角色
 *@Description:
 *@Author: Fan
 *@Date: 2021/1/28 22:06
 @Version 1.0
 *
 */
@Component
public class MySecurityMetadataSource implements FilterInvocationSecurityMetadataSource {

    @Autowired
    SysRoleService sysRoleService;

    //本方法返回访问资源所需的角色集合
    AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Override
    public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException {
        //获得用户访问的路径url
        String requestUrl = ((FilterInvocation) object).getRequestUrl();
        //从数据库中得到所有资源，以及对应的角色
        List<SysRole> resources = sysRoleService.findAll();
        for (SysRole resource : resources) {
            if (antPathMatcher.match(resource.getRolePath(), requestUrl)
                    && resource.getRoles().length > 0) {
                return SecurityConfig.createList(resource.getRoles());
            }
        }
        //如果用户访问的路径没有相关角色权限就代表访问该路径不需要权限
        return SecurityConfig.createList("ROLE_NONE");
    }

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return null;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return FilterInvocation.class.isAssignableFrom(aClass);
    }
}
